package com.jswj.media.task.abs;


import com.jswj.word.domain.WordExt;
import com.jswj.word.service.IWordService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @author wanghonghui
 */
@Slf4j
@Configuration
public abstract class AbstractScreenshot {

    private static AbstractScreenshot screenshot;

    IWordService wordService;


    @Autowired
    public void setService(IWordService wordService) {
        this.wordService = wordService;
    }

    @PostConstruct
    public void init(){
        screenshot = this;
        screenshot.wordService = this.wordService;
    }

    /**
     * 图片保存路径
     */
    //public static String IMG_PATH = "/Users/wanghonghui/Desktop/main/";
    public static String IMG_PATH = "/data/whh/screenshot/images/";

    /**
     * 移动到屏幕中间的js代码
     */
    protected static String SCROLL_ELEMENT_TO_MIDDLE = "var viewPortHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);"
            + "var elementTop = arguments[0].getBoundingClientRect().top;"
            + "window.scrollBy(0, elementTop-(viewPortHeight/2));";

    /**
     * 设置元素样式：边框，颜色，线条
     */
    //protected static String BORDER_STYLE = "arguments[0].setAttribute('style', 'background: red; color: #fff; font-size: 120%;')";
    protected static String BORDER_STYLE = "arguments[0].setAttribute('style', 'border: 2px solid red')";
    /**
     * 截屏url
     */
    protected String URL;

    private static String driverPath;

    static {
        String os = Objects.toString(System.getenv("OS"));
        try {
            if (os.contains("Windows")) {
                driverPath = AbstractScreenshot.class.getResource("/webdriver/windows/chromedriver.exe").getPath();
            } else {
                driverPath = AbstractScreenshot.class.getResource("/webdriver/mac/chromedriver").getPath();
            }
        } catch (Exception e) {
            log.error("未找到chromedriver驱动！");
            throw new RuntimeException("未找到chromedriver驱动！");
        }
    }

    public WebDriver getDriver() {
        if(StringUtils.isBlank(driverPath)) {
            throw new RuntimeException("请先设置浏览器驱动");
        }
        System.setProperty("webdriver.chrome.driver", driverPath);
        ChromeOptions options = new ChromeOptions();
        options.addArguments("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36");
        WebDriver driver = new ChromeDriver(options);
        return driver;
    }

    /**
     * WebDriver截屏
     * @param ele
     * @return
     */
    public File takeScreenshotToFile(WebElement ele) {
        TakesScreenshot takesScreenshot = ele;
        return takesScreenshot.getScreenshotAs(OutputType.FILE);
    }

    public File takeScreenshotToFile(WebDriver ele) {
        TakesScreenshot takesScreenshot = (TakesScreenshot)ele;
        return takesScreenshot.getScreenshotAs(OutputType.FILE);
    }

    public byte[] takeScreenshotToByte(WebElement ele) {
        TakesScreenshot takesScreenshot = ele;
        return takesScreenshot.getScreenshotAs(OutputType.BYTES);
    }

    public String taskScreenshotToBase64(WebDriver ele){
        TakesScreenshot takesScreenshot = (TakesScreenshot)ele;
        return takesScreenshot.getScreenshotAs(OutputType.BASE64);
    }

    /**
     * 保存图片
     * @param bufferedImage
     * @param imgPath
     * @throws IOException
     */
    public void saveImg(BufferedImage bufferedImage, String imgPath) throws IOException{
        ImageIO.write(bufferedImage, "png", new File(imgPath));
    }

    /**
     * 截图
     * @param webDriver
     * @return
     * @throws Exception
     */
    public abstract void takeScreenshot(WebDriver webDriver, List<WordExt> words);

    /**
     * 设置截屏url
     */
    public void setURL(String url){
        URL = url;
    }

    /**
     * 设置元素的样式
     * @param webDriver
     * @param ele
     */
    public void setStyle(WebDriver webDriver, WebElement ele){
        ((JavascriptExecutor) webDriver).executeScript(BORDER_STYLE, ele);
    }

    public void setScrollElementToMiddle(WebDriver webDriver, WebElement ele) {
        ((JavascriptExecutor) webDriver).executeScript(SCROLL_ELEMENT_TO_MIDDLE, ele);
    }

    /**
     * 处理轮播图
     * 如果关键词处于轮播中，需要设置只显示当前这一屏，其他屏全部隐藏
     */
    public void handleCarousel(WebDriver webDriver, WebElement ele, Actions actions) {
        //汽车之家热门车tab页
        try {
            WebElement hotCarElement = ele.findElement(By.xpath("ancestor-or-self::div[contains(@id, 'hotcar-')]"));
            if (null != hotCarElement) {
                List<WebElement> elements = webDriver.findElements(By.cssSelector(".homepage-hotcar .athm-tab__item"));
                if (CollectionUtils.isNotEmpty(elements)) {
                    String id = hotCarElement.getAttribute("id");
                    actions.moveToElement(elements.get(Integer.parseInt(id.replace("hotcar-", "")))).perform();
                    log.warn("热门汽车触发点击事件");
                }
            }
        } catch(Exception e){

        }

        //汽车之家直播滚动效果
        try {
            WebElement liveVideoElement = ele.findElement(By.xpath("ancestor-or-self::li[@class='athm-slide__item']"));
            if (null != liveVideoElement) {
                List<WebElement> elements = liveVideoElement.findElements(By.xpath("preceding-sibling::*"));
                if (CollectionUtils.isNotEmpty(elements)) {
                    WebElement element = ele.findElement(By.xpath("ancestor-or-self::div[@id='live-slide']/div[@class='athm-slide__indicators']/a[" + elements.size() + 1 + "]"));
                    actions.moveToElement(element).perform();
                    log.warn("直播滚动触发点击事件");
                }
            }
        }catch (Exception e){

        }

    }

}
